#include "delay.h"

void DelayInit(void)
{
    /* 关闭 TRC */
    CoreDebug->DEMCR &= ~CoreDebug_DEMCR_TRCENA_Msk;
    /* 打开 TRC */
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;

    /* 关闭计数功能 */
    DWT->CTRL &= ~DWT_CTRL_CYCCNTENA_Msk;
    /* 打开计数功能 */
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;

    /* 计数清零 */
    DWT->CYCCNT = 0;
}

void DelayUs(uint32_t us)
{
    uint32_t tickStart = DWT->CYCCNT;

    /* */
    us *= (SystemCoreClock / 1000000);

    while ((DWT->CYCCNT - tickStart) < us);
}

void DelayMs(uint32_t ms)
{

    for (uint32_t i = 0; i < ms; i++)
    {
        DelayUs(1000);
    }
}
